<template>
  <section class="app-inner">
    <el-dialog
      :show-close="false"
      :visible.sync="previewImageStatus"
      class="preview-image"
    >
      <el-image
        class="my-img"
        v-if="previewImageUrl"
        ref="myImg"
        :src="previewImageUrl"
      >
      </el-image>
    </el-dialog>

    <el-card class="header-card">
      <el-form :inline="true" :model="queryParams" size="small">
        <el-form-item label="民族">
          <el-select
            placeholder="请选择民族"
            v-model="queryParams.nation"
            clearable
            filterable
          >
            <el-option
              v-for="item in comData['民族']"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            placeholder="请选择状态"
            v-model="queryParams.status"
            clearable
            filterable
          >
            <el-option
              v-for="item in comData['账号状态']"
              :key="item.code"
              :label="item.name"
              :value="Number(item.code)"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="学生学籍号">
          <el-input
            v-model="queryParams.code"
            clearable
            placeholder="请输入学生学籍号"
          ></el-input>
        </el-form-item>
        <el-form-item label="学生姓名">
          <el-input
            v-model="queryParams.name"
            clearable
            placeholder="请输入学生姓名"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="
              (e) => {
                this.onSubmit();
              }
            "
            >搜索</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="header-card card-flex">
      <el-button v-if="checkAuthority('/student/add')" type="primary" @click="addStudentInfo">新增学生</el-button>
      <el-button v-if="checkAuthority('/student/download')" type="primary" @click="downLoad">下载模板</el-button>
      <el-upload
        style="display: inline; margin: 0 10px"
        :show-file-list="false"
        action="string"
        :http-request="handleBatchImport"
        :before-upload="beforeUpload"
      >
        <el-button v-if="checkAuthority('/student/batch')" type="primary">批量导入</el-button>
      </el-upload>

      <!-- <el-button type="primary" @click="exportBatch(1)"
        >批量导出Excel</el-button
      > -->
      <el-button v-if="checkAuthority('/student/export')" type="primary" @click="exportBatch(0)">批量导出压缩包</el-button>
      <div v-if="checkAuthority('/eyes')" class="switch-btn cursor iconfont" :class="[isShow ? 'icon-biyan': 'icon-yanjing']" @click="handleClickIsShow"></div>
    </el-card>

    <el-card class="table-card">
      <el-table :data="tableData">
        <el-table-column type="index" />
        <el-table-column
          v-for="item in columns"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
          align="center"
        />
        <el-table-column prop="contact" label="联系方式">
          <template v-slot='{row}'>
            {{ !isShow ? $options.filters.cellularPhone(row.contact) : row.contact || '--' }}
            <!-- {{row.contact | cellularPhone}} -->
          </template>
        </el-table-column>
        <el-table-column prop="accountStatus" label="账号状态">
          <template slot-scope="{ row }">
            <div v-if="row.account">
              <el-switch
                v-model="row.status"
                @change="handleSwitchChange(row.status, row.id)"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#C0C4CC"
              >
              </el-switch>
            </div>
            <div v-else></div>
          </template>
        </el-table-column>

        <el-table-column label="照片">
          <template slot-scope="scope" v-if="scope.row.imageUrl">
            <!-- <img
              :src="scope.row.imageUrl"
              alt=""
              @click="() => doPreviewImg(scope.row.imageUrl)"
              :style="{ 'max-width': '50px', 'max-height': '50px' }"
            /> -->

            <el-image
              :style="{ 'max-width': '50px', 'max-height': '50px' }"
              :src="`/gateway/api/basic/minio/getFileSource?fileName=${scope.row.imageUrl}`"
              :preview-src-list="[
                `/gateway/api/basic/minio/getFileSource?fileName=${scope.row.imageUrl}`,
              ]"
            >
              <div slot="error" class="image-slot"></div>
            </el-image>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- <el-button
              v-if="userInfo.info.userType=='2'"
              @click.native.prevent="infoReset(scope.row)"
              type="text"
              size="small"
              >重置密码</el-button
            > -->
            <el-button
              v-if="checkAuthority('/select')"
              @click.native.prevent="infoSeeing(scope.row)"
              type="text"
              size="small"
              >查看</el-button
            >
            <el-button
              v-if="checkAuthority('/student/update')"
              @click.native.prevent="editInfo(scope.row)"
              type="text"
              size="small"
              >编辑</el-button
            >
            <el-button
              v-if="checkAuthority('/student/delete')"
              @click.native.prevent="infoDel(scope.row)"
              type="text"
              size="small"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        layout="total, prev, pager, next"
        @current-change="pageHandleChange"
        :current-page="currentPage"
        :total="totalPageNum"
      ></el-pagination>
    </el-card>

    <addStudentInfo
      :editDataInfo="infoEdit"
      :editRowID="editRowID"
      :addStudentForm="addStudentForm"
      :data="addStudentFormData"
      :comData="comData"
      :isAdd="isAdd"
      v-if="addStudentForm.flag"
      @closeaddStudentForm="addStudentForm.flag = false"
    />
    <studentInfoForm
      :studentForm="studentForm"
      :data="studentFormData"
      @closestudentForm="studentForm.flag = false"
    />
  </section>
</template>

<script>
import studentInfoForm from './components/studentInfoForm'
import addStudentInfo from './components/addStudentInfo'
import { sepDataDicInfoQuery } from '@/views/children/basic/js/controllerInfo'
import { decrypt } from '@/utils/crypto'
import {
  queryPage,
  downloadTemplate,
  deleteStudent,
  studentsHonorList,
  batchImport,
  exportTeacherInfo,
  updateStudentAccountStatus,
  passwordReset,
  userNoIsBinding
} from '@/views/children/basic/js/studentInfo'
import { checkAuthority } from '@/utils/btnPermission' // 页面按钮权限
export default {
  name: 'studentInfo',
  provide () {
    return {
      handleSearch: () => {
        this.onSubmit(this.currentPage)
      }
    }
  },
  components: {
    studentInfoForm,
    addStudentInfo
  },
  data () {
    return {
      editRowID: 0,
      userInfo: {
        info: JSON.parse(localStorage.getItem('Standard__User-Info')).value
      },
      previewImageStatus: false,
      previewImageUrl: '',
      isAdd: false,
      pageSize: 10,
      currentPage: 1,
      totalPageNum: 0,
      queryParams: {
        code: '',
        name: '',
        nation: '',
        status: ''
      },
      userStates: [],
      tableData: [],
      columns: [
        { label: '学籍号', prop: 'code' },
        { label: '姓名', prop: 'name' },
        { label: '性别', prop: 'genderName' },
        { label: '出生日期', prop: 'birthday' },
        { label: '账号', prop: 'account' },
        // { label: '照片', prop: 'imageUrl' },
        // { label: '联系方式', prop: 'contact' },
        // { label: '账号状态', prop: 'statusName' },
        { label: '民族', prop: 'nationName' }
      ],
      // 查看
      studentForm: {
        flag: false,
        title: ''
      },
      studentFormData: {
        sepSchoolHonorInfoList: [
          {
            name: ''
          }
        ],
        imageUrl: '',
        name: '',
        code: '',
        pinyinName: '',
        englishName: '',
        contact: '',
        address: '',
        status: '',
        isCreateAccount: 1,
        account: '',
        schoolDistrictNo: '',
        gender: '',
        nationality: '',
        cardType: '',
        idCard: '',
        birthday: '',
        birthPlace: [],
        nativePlace: [],

        nation: '',
        politicsStatus: '',
        compatriotCode: '',
        religionCode: '',
        healthCode: '',
        bloodTypeCode: '',
        isOnlyChild: '',
        isMigrantChild: '',
        isOrphan: '',
        isMartyrChild: '',
        isDisabled: '',
        disabledCode: '',
        isBoard: '',
        speciality: '',
        residenceCode: '',
        residenceLocation: [],
        typeCode: '',
        currentStatusCode: '',
        currentSchoolCode: '',
        attendType: '',
        residenceAddress: ''
      },
      addStudentFormData: {
        sepSchoolHonorInfoList: [
          {
            name: ''
          }
        ],
        imageUrl: '',
        name: '',
        code: '',
        pinyinName: '',
        englishName: '',
        contact: '',
        address: '',
        status: '',
        isCreateAccount: 1,
        account: '',
        schoolDistrictNo: '',
        gender: '',
        nationality: '',
        cardType: '',
        idCard: '',
        birthday: '',
        birthPlace: [],
        nativePlace: [],

        nation: '',
        politicsStatus: '',
        compatriotCode: '',
        religionCode: '',
        healthCode: '',
        bloodTypeCode: '',
        isOnlyChild: '',
        isMigrantChild: '',
        isOrphan: '',
        isMartyrChild: '',
        isDisabled: '',
        disabledCode: '',
        isBoard: '',
        speciality: '',
        residenceCode: '',
        residenceLocation: [],
        typeCode: '',
        currentStatusCode: '',
        currentSchoolCode: '',
        attendType: ''
      },
      // 新增
      addStudentForm: {
        flag: false,
        title: ''
      },
      comData: {},
      loading: null,
      isShow: false
    }
  },
  methods: {
    checkAuthority,
    handleClickIsShow () {
      this.isShow = !this.isShow
    },
    editInfo (row) {
      this.editRowID = row
      this.infoEdit(row)
    },
    beforeUpload (file) {
      const extension = file.name.split('.')[1] === 'xls'
      const extension2 = file.name.split('.')[1] === 'xlsx'
      const zipType = file.name.split('.')[1] === 'zip'
      const isLt2M = file.size / 1024 / 1024 < 200
      if (!extension && !extension2 && !zipType) {
        this.$message.warning('导入模板只能是xls、xlsx、zip格式!')
        return false
      } else if (!isLt2M) {
        this.$message.warning('导入模板大小不能超过 200MB!')
        return false
      } else {
        this.loading = this.$loading({
          lock: true,
          text: '正在导入',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.2)'
        })
        return true
      }
    },

    // 账号状态Switch切换
    async handleSwitchChange (status, id) {
      try {
        const res = await updateStudentAccountStatus({
          accountStatus: status,
          id
        })
        if (res.code === 0) {
          this.$message.success('账号状态更新成功！')
          this.onSubmit(this.currentPage)
        }
      } catch (e) { }
    },
    async handleBatchImport (params) {
      // 批量导入
      try {
        const formData = new FormData()
        formData.append('file', params.file)
        const res = await batchImport(formData)
        if (res.code === 0) {
          this.$message.success('导入成功！')
          this.onSubmit(1)
        }
      } catch (e) { }
    },
    async exportBatch (type) {
      let params = {
        code: this.queryParams.code,
        downloadType: type,
        name: this.queryParams.name,
        nation: this.queryParams.nation,
        pageNum: 1,
        pageSize: 10,
        status: this.queryParams.status
      }
      try {
        let res = await exportTeacherInfo(params)

        if (res.code === 0) {
          this.$message.success('导出成功！')
        } else {
          this.$message.error('导出失败！')
        }
      } catch (err) {
        console.log(err)
      }
    },

    doPreviewImg (url) {
      this.previewImageUrl = url
      this.previewImageStatus = true
    },

    // 查询
    onSubmit (page = 1) {
      this.currentPage = page
      let params = {
        code: this.queryParams.code,
        name: this.queryParams.name,
        nation: this.queryParams.nation,
        pageNum: page,
        pageSize: this.pageSize,
        status: this.queryParams.status
      }
      queryPage(params).then((res) => {
        let data = JSON.parse(decrypt(res.data))
        if (data) {
          this.tableData = data.records
          this.totalPageNum = data.total
        }
      })
    },
    // 新增
    addStudentInfo () {
      this.isAdd = false
      this.addStudentForm.flag = true
      this.addStudentForm.title = '新增学生信息'
      this.addStudentFormData = {
        sepSchoolHonorInfoList: [
          {
            name: '',
            awardTime: '',
            level: '',
            awardType: 0,
            rewardsBureau: '',
            awardTermId: '',
            awardLevel: '',
            subjectType: '',
            HonorFileList: [],
            awardPic: ''
          }
        ],
        imageUrl: '',
        name: '',
        code: '',
        pinyinName: '',
        englishName: '',
        contact: '',
        address: '',
        status: '',
        isCreateAccount: 1,
        account: '',
        schoolDistrictNo: '',
        gender: '',
        nationality: '',
        cardType: '1',
        idCard: '',
        birthday: '',
        birthPlace: [],
        nativePlace: [],

        nation: '',
        politicsStatus: '',
        compatriotCode: '',
        religionCode: '',
        healthCode: '',
        bloodTypeCode: '',
        isOnlyChild: '',
        isMigrantChild: '',
        isOrphan: '',
        isMartyrChild: '',
        isDisabled: '',
        disabledCode: '',
        isBoard: '',
        speciality: '',
        residenceCode: '',
        residenceLocation: [],
        typeCode: '',
        currentStatusCode: '',
        currentSchoolCode: '',
        attendType: ''
      }
    },
    // 密码重置
    infoReset (row) {
      this.$confirm('此操作将重置该学生密码 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await passwordReset(row.userNo)
        this.$message.success('重置成功')
        this.onSubmit(this.currentPage)
      })
    },
    // 查看
    async infoSeeing (row) {
      const { data, code, msg } = await studentsHonorList({
        schoolNo: row.schoolNo,
        studentNo: '',
        studentCode: row.code
      })

      if (code === 0) {
        this.studentFormData = {
          ...row,
          schoolNo: row.schoolNo,
          studentNo: row.no,
          sepSchoolHonorInfoList: data.map((item) => {
            return {
              ...item,
              HonorFileList: item.awardPic
                ? item.awardPic.split(',').map((item, index) => {
                  return {
                    name: Date().now + index + '.png',
                    response: { code: 0, data: item, msg: 'success' },
                    url: item
                  }
                })
                : []
            }
          })
        }
      } else {
        this.studentFormData = {
          ...row,
          schoolNo: row.schoolNo,
          studentNo: row.no,
          sepSchoolHonorInfoList: []
        }
        this.$message.warning(msg)
      }

      this.studentForm.flag = true
      this.studentForm.title = row.title
    },

    setRegionTextToCode (region) {
      if (region) {
        return region.split(',')
      }
    },
    // 编辑
    async infoEdit (row) {
      const { data, code, msg } = await studentsHonorList({
        schoolNo: row.schoolNo,
        studentNo: '',
        studentCode: row.code
      })
      if (code === 0) {
        this.addStudentFormData = {
          ...row,
          nativePlace: this.setRegionTextToCode(row.nativePlace),
          birthPlace: this.setRegionTextToCode(row.birthPlace),
          residenceLocation: this.setRegionTextToCode(row.residenceLocation),
          fileList: row.imageUrl
            ? [{ name: row.imageUrl + '.png', url: row.imageUrl }]
            : [],
          schoolNo: row.schoolNo,
          studentNo: row.no,
          sepSchoolHonorInfoList: data.map((item) => {
            return {
              ...item,
              HonorFileList: item.awardPic
                ? item.awardPic.split(',').map((item, index) => {
                  return {
                    name: Date().now + index + '.png',
                    response: { code: 0, data: item, msg: 'success' },
                    url: item
                  }
                })
                : []
            }
          })
        }
      } else {
        this.addStudentFormData = {
          ...row,
          schoolNo: row.schoolNo,
          studentNo: row.no,
          sepSchoolHonorInfoList: []
        }

        this.$message.warning(msg)
      }

      this.isAdd = true
      this.addStudentForm.flag = true
      this.addStudentForm.title = '编辑学生信息'
    },
    // 删除当前行的学生信息
    infoDel (row) {
      this.$confirm('此操作将删除该学生信息 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await userNoIsBinding({ userNo: row.no, userType: 1 })
        if (res.data) {
          this.$confirm(' 已绑定沪学通小程序，是否确认删除?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.deleteStudent(row.id)
          })
        } else {
          this.deleteStudent(row.id)
        }
      })
    },
    async deleteStudent (id) {
      await deleteStudent(id)
      this.$message.success('删除成功')
      this.onSubmit(this.currentPage)
    },
    // 分页
    pageHandleChange (page) {
      this.currentPage = page
      this.onSubmit(page)
    },
    init () {
      sepDataDicInfoQuery().then((res) => {
        let data = res.data
        if (data) {
          this.comData = data
        }
      })
    },
    downLoad () {
      downloadTemplate()
    }
  },
  mounted () {
    this.init()
    this.onSubmit()
  }
}
</script>

<style lang="scss" scoped>
.app-inner {
  /deep/ .preview-image {
    .el-dialog__header {
      display: none;
    }
    .el-dialog__body {
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .my-img {
      width: 300px;
    }
  }

  .header-card {
    margin-bottom: 10px;
  }
  .el-pagination {
    text-align: center;
    display: block;
    margin: 10px auto;
  }
}
</style>
